package com.example.applicationnews;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

public class MyAdapter extends BaseAdapter{

    private ArrayList<Stars> starsArrayList;
    private Context mContext;

    public MyAdapter(ArrayList<Stars> starsArrayList, Context mContext) {
        this.starsArrayList = starsArrayList;
        this.mContext = mContext;
    }

    @Override
    public int getCount() {
        return starsArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 为每一条新闻赋值
        ViewHolder viewHolder;
        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_listview_item,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.news_author = (TextView) convertView.findViewById(R.id.tv_news_author);
            viewHolder.news_title = (TextView) convertView.findViewById(R.id.tv_news_title);
            viewHolder.news_pic = (ImageView) convertView.findViewById(R.id.iv_news_pic);
            viewHolder.news_time = (TextView)convertView.findViewById(R.id.tv_news_time);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }
        String pic_url = starsArrayList.get(position).getNews_pic();
        // 使用 Glide 异步加载图片
        Glide.with(mContext)
                .load(pic_url)
                .into(viewHolder.news_pic);
        viewHolder.news_title.setText(starsArrayList.get(position).getNews_title());
        viewHolder.news_author.setText(starsArrayList.get(position).getNews_author());
        viewHolder.news_time.setText(starsArrayList.get(position).getNews_time());
        return convertView;
    }

    public Bitmap getLocalOrNetBitmap(String url) {
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher_foreground);
        if (url != null) {
            InputStream in = null;
            BufferedOutputStream out = null;
            try
            {
                //读取图片输入流
                in = new BufferedInputStream(new URL(url).openStream(), 2 * 1024);
                //准备输出流
                final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                out = new BufferedOutputStream(dataStream, 2 * 1024);
                byte[] b = new byte[1024];
                int read;
                //将输入流变为输出流
                while ((read = in.read(b)) != -1) {
                    out.write(b, 0, read);
                }
                out.flush();
                //将输出流转换为bitmap
                byte[] data = dataStream.toByteArray();
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                data = null;
                return bitmap;
            }
            catch (IOException e)
            {
                e.printStackTrace();
                return bitmap;
            }
        }
        return bitmap;
    }

    private void asyncLoadImage(final ImageView imageView, final String uri) {
        @SuppressLint("HandlerLeak") final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    Bitmap bitmap = (Bitmap) msg.obj;
                    if (imageView != null && uri != null) {
                        imageView.setImageBitmap(bitmap);
                    }

                }
            }
        };
        // 子线程，开启子线程去下载或者去缓存目录找图片，并且返回图片在缓存目录的地址
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    //这个URI是图片下载到本地后的缓存目录中的URI
                    if (uri != null ) {
                        Bitmap bitmap = getLocalOrNetBitmap(uri);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = bitmap;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
    }

    private static class ViewHolder{
        TextView news_title;
        TextView news_author;
        ImageView news_pic;
        TextView news_time;
    }

}

